﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SubstrateHelper.Data;

namespace SubstrateHelper.Areas.Identity.Pages.Account.Manage
{
    public partial class IndexModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;

        SubstrateHelperDbContext Db;


        public IndexModel(
           
            UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            SubstrateHelperDbContext db)
        {

            Db = db;
             _userManager = userManager;
            _signInManager = signInManager;
        }

        [Display(Name = "姓名")]
        public string UserId { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        [BindProperty]
        public InputModel Input { get; set; }

        //
        public IdentityUserRole<string>[] UserRoles { get; set; }
        public IdentityRoleClaim<string>[] RoleClaims { get; set; }

        public class InputModel
        {
            [Phone]
            [Display(Name = "手机号码")]
            public string PhoneNumber { get; set; }
        }

        private async Task LoadAsync(IdentityUser user)
        {           

            UserId = user.Id;

            Input = new InputModel
            {
                PhoneNumber = user.UserName
            };
        }

        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
           
            if (user == null)
            {
                return NotFound($"找不到用户： '{_userManager.GetUserId(User)}'.");
            }

            //
            UserRoles = Db.UserRoles.Where(ur => ur.UserId == user.Id).OrderBy(ur=>ur.RoleId).ToArray();
            RoleClaims = Db.RoleClaims
                .Join(Db.UserRoles, rc => rc.RoleId, ur => ur.RoleId, (rc, ur) => new { rc, ur })
                .Where(item => item.ur.UserId == user.Id)
                .Select(item => item.rc)
                .OrderBy(ur => ur.RoleId)
                .ThenBy(rc=>rc.ClaimType)
                .ThenBy(rc=>rc.ClaimValue)
                .ToArray();
            //

            await LoadAsync(user);
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {            
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"找不到用户 '{_userManager.GetUserId(User)}'.");
            }

            
            if (!ModelState.IsValid)
            {
                await LoadAsync(user);
                return Page();
            }

            var phoneNumber = await _userManager.GetUserNameAsync(user);//姓名用Id存储，电话号码用UserName存储
            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetUserNameAsync(user, Input.PhoneNumber);
                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);
                    throw new InvalidOperationException($"当修改用户'{userId}'的手机号码时，遇到未知错误！");
                }
            }

            await _signInManager.RefreshSignInAsync(user);
            StatusMessage = "手机号码修改成功。";
            return RedirectToPage();
        }
    }
}
